package com.zhj.common.web.apiversion;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * 多版本请求条件
 * @author zhj
 */
@Slf4j
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    private Double version;

    private final String VERSION_NAME = "api-version";

    public Double getVersion() {
        return this.version;
    }

    public ApiVersionRequestCondition(Double version) {
        this.version = version;
    }

    /**
     * 当类上的条件和方法上条件同时存在时，方法的优先级高
     * @param other
     * @return
     */
    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
        return other;
    }

    /**
     * 根据请求返回符合条件的RequestCondition对象，没有则返回null
     * @param httpServletRequest
     * @return
     */
    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest httpServletRequest) {
        Double reqVersion = 1.0;
        String apiVersion = httpServletRequest.getHeader(VERSION_NAME);
        if (StringUtils.isEmpty(apiVersion))
            apiVersion = httpServletRequest.getParameter(VERSION_NAME);
        try {
            if (!StringUtils.isEmpty(apiVersion))
                reqVersion = Double.valueOf(apiVersion);
        } catch (NumberFormatException e) {
            log.info("版本号应该是数字类型，传错按1.0版本执行！");
        }
        if (this.getVersion() <= reqVersion)
            return this;
        return null;
    }

    /**
     * 排序 - 为了选择最优的请求条件对象
     * @param other
     * @param httpServletRequest
     * @return 版本号相对较大
     */
    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest httpServletRequest) {
        return Double.compare(other.getVersion(), this.getVersion());
    }
}
